<template>
    <div class="content">
        <el-card style="border:none !important;border-radius: 12px;box-shadow:none !important">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item :to="{ path: '/userhome' }">个人中心</el-breadcrumb-item>
                <el-breadcrumb-item>
                    <a href="/account_sys">账户管理</a>
                </el-breadcrumb-item>
                <el-breadcrumb-item>账号与密码</el-breadcrumb-item>
            </el-breadcrumb>
            <div class="tab-nav-bd">
                <span class="title">账号与密码</span>
            </div>
        </el-card>

        <div class="right-safe-content" style="margin-top: 20px;">
            <div class="left-info">
                <div class="user-photo">
                    <el-upload class="avatar-uploader" accept="image/*" :http-request="handleUpload"
                        :before-upload="handleChange" ref="uploadRef" :show-file-list="false">
                        <img class="user-img" :src="userInfo.avatar" alt="" />

                    </el-upload>

                </div>
                <div class="ll-age">
                    入驻<span>{{userInfo.regDay}}天</span>
                </div>
            </div>
            <div class="right-info">
                <div class="row" style="margin: 44px 0 23px;">
                    <div class="row-title"><span class="red">*</span>昵称</div>
                    <div class="row-con">
                        <div class="left-col title user-name-val">
                            {{ userInfo.username }} </div>
                        <div @click="editUserName('用户昵称', 'username')" class="right-col">编辑</div>
                    </div>
                </div>
                <div class="row" style="margin: 44px 0 23px;">
                    <div class="row-title"><span class="red">*</span>用户ID</div>
                    <div class="row-con">
                        <div class="left-col title user-name-val">
                            {{ userInfo.label_id }} </div>
                        <!-- <div class="right-col">编辑</div> -->
                    </div>
                </div>
                <!-- <div class="row" style="margin: 44px 0 23px;">
                    <div class="row-title"><span class="red">*</span>您的职位</div>
                    <div class="row-con">
                        <div class="left-col title user-name-val">
                            。 </div>
                        <div class="right-col">编辑</div>
                    </div>
                </div> -->
                <div class="row" style="margin: 44px 0 23px;">
                    <div class="row-title"><span class="red">*</span>登录密码</div>
                    <div class="row-con">
                        <div class="left-col  user-name-val">
                            <span class="title">{{ userInfo.isSetPwd ? '强' : '未设置登录密码' }} </span>
                            <span class="pwd-tip">强烈建议经常修改密码，提升账号安全等级</span>
                        </div>

                        <div class="right-col" @click="updatePwdClick('修改密码')">编辑</div>
                    </div>
                </div>
                <div class="row" style="margin: 44px 0 23px;">
                    <div class="row-title"><span class="red">*</span>绑定邮箱</div>
                    <div class="row-con">
                        <div class="left-col title user-name-val">
                            <el-tooltip class="box-item" effect="dark"
                                :content="userInfo.email ? userInfo.email : '未绑定邮箱'" placement="top">
                                {{ userInfo.email ? userInfo.email : '未绑定邮箱' }}
                            </el-tooltip>
                        </div>
                        <div class="right-col" @click="editUserName('绑定邮箱', 'email')">编辑</div>
                    </div>
                </div>
                <div class="row" style="margin: 44px 0 23px;">
                    <div class="row-title"><span class="red">*</span>绑定手机号</div>
                    <div class="row-con">
                        <div class="left-col title user-name-val">
                           {{  userInfo.mobile ? maskedPhoneNumber : '未绑定手机号'}} </div>
                        <div class="right-col" @click="updateMobile">编辑</div>
                    </div>
                </div>
            </div>
        </div>
        <!--username and 邮箱 弹窗 -->
        <el-dialog v-model="dialogVisible" append-to-body :title="title" align-center modal-class="overlay-modal"
            :close-on-press-escape="false" :close-on-click-modal="false" width="500">
            <div v-if="userType == 'username'">
                <el-input v-model="username" placeholder="请输入用户名" />
            </div>
            <div v-else>
                <el-input v-model="userEmail" placeholder="请输入邮箱地址" />
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitClick">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <!--修改密码弹窗 -->
        <el-dialog v-model="dialogVisiblePwd" append-to-body align-center modal-class="overlay-modal" title="设置密码"
            :close-on-press-escape="false" :close-on-click-modal="false" width="500">
            <div style="line-height:70px;">
                <div>
                    <el-input v-model="maskedPhoneNumber" placeholder="请输入手机号" disabled />
                </div>
                <div>
                    <el-input v-model="code" placeholder="请输入验证码">
                        <template #append> <el-button @click="getSendCode">{{ btnText }}</el-button></template>
                    </el-input>
                </div>
                <div>
                    <el-tooltip class="box-item" effect="dark" content="密码必须由至少一个小写字母、一个大写字母和一个数字组成，且长度在6到16位之间"
                        placement="bottom">
                        <el-input type="password" show-password v-model="password" placeholder="密码长度6-16位" />
                    </el-tooltip>
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisiblePwd = false">取消</el-button>
                    <el-button type="primary" @click="submitPwdClick">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <!--更换手机弹窗 -->
        <el-dialog v-model="dialogVisibleMobile" append-to-body align-center modal-class="overlay-modal" title="绑定手机号"
            :close-on-press-escape="false" :close-on-click-modal="false" width="500">
            <div style="line-height:70px;">
                <div>
                    <el-input v-model="userMobile" placeholder="请输入手机号" />
                </div>
                <div>
                    <el-input v-model="code" placeholder="请输入验证码">
                        <template #append> <el-button @click="getSendCode">{{ btnText }}</el-button></template>
                    </el-input>
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisibleMobile = false">取消</el-button>
                    <el-button type="primary" @click="submitClick">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>

</template>
<script setup lang="ts">
import { ref, computed, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { useUserInfo } from '../../stores/userInfo'
import { updateUserInfo, setPassword,updateAvatar,userDay } from '../../api/user/index'
import { sendMobileCode, doLogout } from '../../api/home/index'
import router from '../../router'
import { Local } from '../../utils/storage'
const userInfo = useUserInfo() //获取用户信息
const dialogVisible = ref(false)
const dialogVisiblePwd = ref(false)
const dialogVisibleMobile = ref(false)
const title = ref('修改')
const userType = ref('username')
const username = ref('') //用户名
const userEmail = ref('') //用户邮箱
const userMobile = ref('') //用户手机号
const code = ref(''); //验证码
const password = ref('') //用户密码
//编辑用户信息
const editUserName = (str: string, type: string) => {
    title.value = str
    userType.value = type
    if (userType.value == 'username') {
        username.value = userInfo.username
    } else {
        userEmail.value = userInfo.email
    }
    dialogVisible.value = true
}

const userDayNum = ref(0)
//获取用户的入驻天数
userDay({}).then((res:any)=>{
    if(res.code == 1){
        userDayNum.value = res.data.day
    }
})



// 计算属性：将手机号中间四位替换为星号  
const maskedPhoneNumber = computed(() => {
    if(userInfo.mobile){
        return userInfo.mobile.slice(0, 3) + '****' + userInfo.mobile.slice(-4);
    }
   
});

//更换手机
const updateMobile = () => {
    code.value = ''
    stopCountingDown()
    userType.value = 'mobile'
    userMobile.value = userInfo.mobile
    dialogVisibleMobile.value = true
}

//修改密码弹窗
const updatePwdClick = (str: string) => {
    code.value = ''
    title.value = str
    userType.value = 'password'
    stopCountingDown()
    dialogVisiblePwd.value = true
}

//按钮提交
const submitClick = () => {
    if (username.value === '' && userType.value == 'username') {
        ElMessage.error('请填写昵称，昵称不能为空')
        return
    }
    if (userEmail.value === '' && userType.value == 'email') {
        ElMessage.error('请填写邮箱，邮箱不能为空')
        return
    }
    if (userMobile.value === '' && userType.value == 'mobile') {
        ElMessage.error('请填写手机号，手机号不能为空')
        return
    }
    if (code.value === '' && userType.value == 'mobile') {
        ElMessage.error('请填写验证码')
        return
    }
    let obj = { type: userType.value, username: username.value, email: userEmail.value, mobile: userMobile.value, code: code.value }
    //修改用户信息
    updateUserInfo(obj).then((res:any) => {
        if (res.code == 1) {
            if (userType.value == 'username') {
                userInfo.username = username.value
            } else if (userType.value == 'email') {
                userInfo.email = userEmail.value
            } else {
                userInfo.mobile = userMobile.value
            }
            ElMessage.success('修改成功')
        } else {
            ElMessage.error('修改失败')

        }
        dialogVisible.value = false
        dialogVisibleMobile.value = false
    }).catch((error) => {
        if (error.code === 0) {
            ElMessage.error(error.msg)
        } else if (error.code === 'ERR_CANCELED') {
            ElMessage.error("请求错误")
        } else {
            ElMessage.error("未知错误")
        }

    });

}
//验证密码规则
const submitPwdClick = () => {
    const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{6,16}$/;
    if (code.value === '') {
        ElMessage.error('验证码不能为空')
        return
    }
    if (password.value === '') {
        ElMessage.error('密码不能为空')
        return
    }
    if (!regex.test(password.value)) {
        ElMessage.error('密码必须由至少一个小写字母、一个大写字母和一个数字组成，且长度在6到16位之间')
        return
    }
    setPassword({ code: code.value, password: password.value }).then((res:any) => {
        if (res.code == 1) {
            ElMessage.success(res.msg)
            dialogVisiblePwd.value = false
            setTimeout(() => {
                doLogin()
            }, 2000); // 延迟2秒后修改message

        }
    })
}
const doLogin = () => {
    doLogout({ refreshToken: userInfo.refreshToken }).then((res) => {
        Local.remove('userInfo')
        router.go(0)
    })
}
//倒计时
const totalTime = 60                // 倒计时时间
const countingDown = ref(false)     // 倒计时状态
// 倒计时剩余时间
const remainingTime = reactive({
    seconds: totalTime
})
// 计时器变量
let timer: NodeJS.Timeout | null = null
// 倒计时
const startCountingDown = () => {
    if (!countingDown.value) {
        countingDown.value = true
        remainingTime.seconds = totalTime
    }
    timer = setInterval(() => {
        if (remainingTime.seconds > 0) {
            remainingTime.seconds--
        } else {
            stopCountingDown()
        }
    }, 1000)
}

// 倒计时停止
const stopCountingDown = () => {
    if (timer) {
        clearInterval(timer)
        timer = null
        countingDown.value = false
    }
}
// 按钮文字切换
const btnText = computed(() => (countingDown.value ? remainingTime.seconds + '秒后重发' : "获取验证码"))
//获取验证码
const getSendCode = () => {
    code.value = '' //设置空
    try {
        sendMobileCode({ mobile: userType.value == 'password' ? userInfo.mobile : userMobile.value, status: 1, type: userType.value }).then((res:any) => {
            if (res.code == 1) {
                startCountingDown()
                code.value = res.data.list
            } else {
                ElMessage.error(res.msg)
            }
        }).catch((error) => {
        if (error.code === 0) {
            ElMessage.error(error.msg)
        } else if (error.code === 'ERR_CANCELED') {
            ElMessage.error("请求错误")
        } else {
            ElMessage.error("未知错误")
        }
    });
    } catch {
        ElMessage.error('验证码发送失败')
    }
}
// 上传验证
const handleChange = (rawFile: any) => {
    if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
        ElMessage.error("只能上传jpeg/jpg/png图片");
        return false;
    } else if (rawFile.size / 1024 / 1024 > 1) {
        ElMessage.error("上传图片最大不超过1MB!");
        return false;
    }
    return true;
};
//提交方法
const handleUpload = (file: any) => {
    let fd = new FormData();
    fd.append("file", file.file);
    updateAvatar(fd).then((res:any) =>{
       if(res.code == 1){
            userInfo.avatar = res.data.file.full_url
       }
    })
};
</script>
<style scoped lang="scss">
.right-safe-content {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    padding: 21px 32px 52px 24px;
    /* width: 100%; */
    background: #FFF;
    border-radius: 12px;
}

.right-safe-content .user-img {
    width: 150px;
    height: 150px;
    -webkit-box-shadow: 0 4px 10px 0 rgba(0, 0, 0, .1);
    box-shadow: 0 4px 10px 0 rgba(0, 0, 0, .1);
    border: 6px solid #FFF;
    border-radius: 50%;
    cursor: pointer;
}

.right-safe-content .ll-age {
    margin-top: 10px;
    width: 150px;
    font-size: 14px;
    color: #86909C;
    line-height: 22px;
    text-align: center;
}

.right-safe-content .right-info {
    -webkit-box-flex: 1;
    -ms-flex: 1;
    flex: 1;
    margin-left: 32px;
}

.right-safe-content .row:hover {
    margin: 0 -16px;
    padding: 0 16px;
    background: #F2F3F5;
    border-radius: 12px
}

.right-safe-content .row-title {
    padding: 16px 0 7px;
    font-size: 14px;
    color: #86909C;
    line-height: 22px;
}

.right-safe-content .row-title .red {
    color: #F93434;
}

.right-safe-content .row-con {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-pack: justify;
    -ms-flex-pack: justify;
    justify-content: space-between;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    padding-bottom: 5px;
    border-bottom: 1px solid #F2F3F5;
}

.right-safe-content .row-con .title {
    display: inline-block;
    width: 120px;
    font-size: 14px;
    color: #1D2129;
    height: 32px;
    overflow: hidden;
    line-height: 32px;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.right-safe-content .row-con .right-col {
    font-size: 14px;
    color: #86909C;
    line-height: 22px;
    cursor: pointer;
}

.tab-nav-bd {
    margin-top: 16px;
}

.tab-nav-bd .title {
    font-size: 18px;
    font-weight: 700;
    color: #1D2129;
    line-height: 26px;
}

.pwd-tip {
    display: inline-block;
    margin-left: 72px;
    line-height: 32px;
    height: 32px;
    overflow: hidden;
    color: #FF7D00;
}

.login .normal .normal-login .reset-pwd-text {
    font-size: 14px;
    color: #FDA333;
    margin-bottom: 40px;
    line-height: 14px;
}

/* 设置客户管理模块的高度和固定位置 */

.overlay-modal {
    position: absolute;
    width: 300px;
    height: 200px;
    left: 50%;
    top: 50%;
    background: #fff;
    border: 1px solid rgba(0, 0, 0, 0.2);
    box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5);
    border-radius: 6px;
    text-align: center;
    margin-left: -150px;
    margin-top: -100px;
}
</style>